<template>
  <view class="authorize-wrapper">
    <image class="logo" :src="settings.logo_authorize" mode="widthFix" />
    <view
      class="desc"
    >说明：本小程序为内部员工考核管理工具，无法提供浏览功能，使用本小程序前需先进行微信授权，我们无权引导您微信授权，您也可以点击下方拒绝微信登录按钮，将退出小程序。</view>
    <view class="text">申请获取以下权限</view>
    <view class="text">获得你的公开信息（昵称、头像等）</view>
    <button
      class="button bgc-theme"
      open-type="getUserInfo"
      @getuserinfo="getUserInfo"
      v-if="!canIUseGetUserProfile"
    >
      <text class="button-icon">&#xe686;</text>
      <text>微信一键授权</text>
    </button>
    <button
      class="button bgc-theme"
      :disabled="disabled"
      @click="getUserProfile"
      v-if="canIUseGetUserProfile"
    >
      <text class="button-icon">&#xe686;</text>
      <text>微信一键授权</text>
    </button>
    <navigator class="navigator cancel" open-type="exit" target="miniProgram">
      <text style="text-align: center">拒绝微信授权</text>
    </navigator>
    <view class="tip" @tap="show">《{{ settings.name }}用户协议》</view>
  </view>
</template>
<script>
import { weixinCheck } from "@/services/auth";
import { mapState } from "vuex";
export default {
  data() {
    return {
      canIUseGetUserProfile: false,
      jsCode: null,
      disabled: false
    };
  },
  computed: {
    ...mapState(["settings"])
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.canIUseGetUserProfile = true;
    }
  },
  created() {
    uni.login({
      provider: "weixin",
      success: loginRes => {
        this.jsCode = loginRes.code;
      }
    });
  },
  methods: {
    getUserProfile: function(e) {
      this.disabled = true;
      wx.getUserProfile({
        desc: "获取你的昵称、头像、地区及性别", // 不写不弹提示框
        success: res => {
          uni.showLoading({
            title: "信息验证中...",
            mask: true
          });
          this.disabled = false;
          const data = {
            iv: res.iv,
            encryptedData: res.encryptedData,
            jsCode: this.jsCode
          };
          weixinCheck(data);
          uni.hideLoading();
        },
        fail: res => {
          this.disabled = false;
          // 拒绝授权
          wx.showToast({
            title: "您拒绝了授权",
            icon: "none"
          });
          return;
        }
      });
    },
    getUserInfo(res) {
      if (res.detail && res.detail["iv"] && res.detail["encryptedData"]) {
        const data = {
          iv: res.detail.iv,
          encryptedData: res.detail.encryptedData,
          jsCode: this.jsCode
        };
        weixinCheck(data);
      } else {
        uni.showToast({
          title: "微信授权失败",
          icon: "none",
          duration: 2000
        });
      }
    },
    show() {
      uni.navigateTo({
        url: "/authorize/service"
      });
    }
  }
};
</script>
